function sumOfSquares(n) {
    if (is_square(n)) return 1;
    // The result is 4 if n can be written in the 
    // form of 4^k*(8*m + 7).
    while ((n & 3) == 0) // n%4 == 0  
    { n >>= 2; }
    if ((n & 7) == 7) // n%8 == 7
    { return 4; }
    for (var i = 1; i <= parseInt(Math.sqrt(n)); i++) {
        if (is_square(n - i * i)) return 2;
    }
    return 3;
}

function is_square(x) {
    var root = Math.sqrt(x);
    return root % 1 === 0
}

console.log(sumOfSquares(17))